//
//  squareViewController.m
//  FastRunDemo
//
//  Created by 苟亚明 on 16/9/16.
//  Copyright © 2016年 苟亚明. All rights reserved.
//

#import "squareViewController.h"
#import "XCPullMenu.h"
#import "squareTableView.h"
#import <MJRefresh.h>
#import "squareTableViewCell.h"
#import "squarePicCell.h"
#import "CommentViewController.h"
#import "KPNaviViewController.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import "squareList.h"
#import "squareLeftMenuView.h"
#import "squareRightMenuView.h"
#import "XMGTopWindow.h"

@interface squareViewController () <XCPullMenuDelegate,UITableViewDelegate,UITableViewDataSource>
/** 下拉菜单*/
@property (nonatomic, strong) XCPullMenu *menu;

/** 左滑菜单*/
@property (nonatomic, strong) squareLeftMenuView *leftMenuView;

/** 右滑菜单*/
@property (nonatomic, strong) squareRightMenuView *rightMenuView;

/** 保存数据的数组*/
@property (nonatomic, strong) NSArray *arrCatogeries;
/** tableView*/
@property (nonatomic, strong) squareTableView *tableView;

/** 上一次的请求参数 */
@property (nonatomic, strong) NSDictionary *params;

/** AFN请求管理者*/
@property (nonatomic, strong) AFHTTPSessionManager *manager;

@property (nonatomic, strong) NSMutableArray *topics;

/** 上一次请求返回的参数 */
@property (nonatomic, copy) NSString *maxtime;
@end

static UIWindow *window_;

@implementation squareViewController
#pragma mark - viewLife
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    window_.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    window_ = nil;
    window_.hidden = YES;
    [window_ removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置状态栏
    [self setupStateBar];
    
    // 设置导航栏
    [self setupNavi];
    
    // 设置tableView
    [self setupTableView];
    
    // 设置右滑菜单
    self.rightMenuView = [[squareRightMenuView ShareRightMenuView]initWithCotainerViewController:self];
    [self.navigationController.view addSubview:self.rightMenuView];
    
}
/**
 * 设置状态栏
 */
- (void)setupStateBar{
    
    window_ = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, GYMScreenW, 20)];
    
    window_.windowLevel = UIWindowLevelAlert;
    
    window_.backgroundColor = [UIColor clearColor];
    
    UITapGestureRecognizer *tapClickTwo = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowClick)];
    
    [tapClickTwo setNumberOfTapsRequired:2];
    
    [window_ addGestureRecognizer:tapClickTwo];
    
    window_.hidden = NO;
}


/**
 * 状态栏按钮点击事件
 */
- (void)windowClick{
    
    [self.tableView setContentOffset:CGPointZero animated:YES];
    
}

/**
 * 设置导航栏
 */
- (void)setupNavi{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"square_navi_message" highImage:@"square_navi_message" target:self action:@selector(leftBtnClick)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"square_navi_search" highImage:@"square_navi_search" target:self action:@selector(rightBtnClick)];
    
    self.arrCatogeries = @[@"全部",@"我能帮",@"生活动态",@"闲置",@"失物招领",@"活动",@"咨询"];
}
static NSString *const sqarePicID = @"sqarePicIDCell";
static NSString *const sqareID = @"sqareIDCell";
/**
 * 设置tableView
 */
- (void)setupTableView{
    squareTableView *tableView = [[squareTableView alloc]initWithFrame:CGRectMake(0, 64, GYMScreenW, GYMScreenH - 64 - 49)];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView registerNib:[UINib nibWithNibName:@"squareTableViewCell" bundle:nil] forCellReuseIdentifier:sqareID];
    [tableView registerNib:[UINib nibWithNibName:@"squarePicCell" bundle:nil] forCellReuseIdentifier:sqarePicID];

    tableView.estimatedRowHeight = 66;
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 设置刷新控件
    [self setupRefresh];
}


/**
 * 设置刷新控件
 */
- (void)setupRefresh{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.automaticallyHidden = NO;
    
    
}

- (void)loadMoreData{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.tableView reloadData];
//        [self.tableView.mj_footer endRefreshing];
//    });
    // 停止下拉刷新
    [self.tableView.mj_header endRefreshing];
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"newlist";
    params[@"c"] = @"data";
    params[@"type"] = @(29);
    params[@"maxtime"] = self.maxtime;
    self.params = params;
    
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        if (self.params != params) return;
        
        
        NSArray *model = [squareList mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [self.topics addObjectsFromArray:model];
        
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [self.tableView.mj_footer endRefreshing];
    }];

}
- (void)loadNewData
{
    
    // 停止上拉刷新
    [self.tableView.mj_header endRefreshing];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"newlist";
    params[@"c"] = @"data";
    params[@"type"] = @(29);
    self.params = params;
    
    
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        if (self.params != params) return;
        
        
        self.topics = [squareList mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
    }];

    
}


#pragma mark - action
- (void)rightBtnClick{
    
    if (self.rightMenuView.isRightViewHidden) {
        [self.rightMenuView openRightMenuView];
    }else{
        [self.rightMenuView closeRightMenuView];
    }

}

- (void)leftBtnClick{
    
    __weak __typeof(self) weakSelf = self;
    if (!_menu) {
        
        XCPullMenu *pullMenu = [[XCPullMenu alloc]initWithDataArr:@[@"我的好友"] origin:CGPointMake(0, 64) width:120 rowHeight:44];
        pullMenu.delegate = self;
        self.menu = pullMenu;
        _menu.dismiss = ^() {
            weakSelf.menu = nil;
        };
        //    [[UIApplication sharedApplication].keyWindow.window addSubview:pullMenu];
        
        GYMLog(@"leftBtnClick");
        [self.view addSubview:pullMenu];
    }else{
        [_menu dismissWithCompletion:^(XCPullMenu *object) {
            weakSelf.menu = nil;
        }];
    }
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.topics.count == 0;
    return self.topics.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    squareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sqareID];
    cell.topics = self.topics[indexPath.row];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    squareList *topic = self.topics[indexPath.row];
    CommentViewController *vc = [[CommentViewController alloc]init];
    vc.topics = topic;
    [self.navigationController pushViewController:vc animated:NO];

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
}


#pragma mark - <XCPullMenuDelegate>
- (void)XCPullMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}


#pragma mark - setter&&getter

- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

-(NSMutableArray *)topics{
    if (!_topics) {
        _topics = [NSMutableArray array];
    }
    return _topics;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"frame"];
}

@end
